package cn.myj2c.executor.defined;

import cn.myj2c.executor.Context;
import cn.myj2c.executor.MethodExecutor;
import cn.myj2c.executor.providers.MethodProvider;
import cn.myj2c.executor.values.JavaObject;
import cn.myj2c.executor.values.JavaValue;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MappedMethodProvider extends MethodProvider {
    private Map<String, ClassNode> classpath = new HashMap<>();

    public MappedMethodProvider(Map<String, ClassNode> classpath) {
        this.classpath = classpath;
    }

    public boolean canInvokeMethod(String className, String methodName, String methodDesc, JavaValue targetObject, List<JavaValue> args, Context context) {
        ClassNode classNode = classpath.get(className);
        if(classNode == null)
        	return false;
        MethodNode methodNode = classNode.methods.stream().filter(mn -> mn.name.equals(methodName) && mn.desc.equals(methodDesc)).findFirst().orElse(null);
        return methodNode != null;
    }

    @Override
    public Object invokeMethod(String className, String methodName, String methodDesc, JavaValue targetObject, List<JavaValue> args, Context context) {
        ClassNode classNode = classpath.get(className);
        if (classNode != null) {
            MethodNode methodNode = classNode.methods.stream().filter(mn -> mn.name.equals(methodName) && mn.desc.equals(methodDesc)).findFirst().orElse(null);
            if (methodNode != null) {
                List<JavaValue> argsClone = new ArrayList<>();
                for (JavaValue arg : args) {
                    argsClone.add(arg.copy());
                }
                return MethodExecutor.execute(classNode, methodNode, argsClone, targetObject == null ? new JavaObject(null, "java/lang/Object") : targetObject, context);
            }
            throw new IllegalArgumentException("Could not find method " + methodName + methodDesc);
        }
        throw new IllegalArgumentException("Could not find class " + className);
    }
}
